package com.guoqing.example.config;

import com.guoqing.example.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName WebSecurityConfig
 * @Description TODO
 * @Author ZhangGuoQing
 * @Date 2020/8/21/0021 15:59
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启需要方法授权
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailService myUserDetailService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 所有 security 全注解配置实现的开端，表示说明需要的权限 需要的权限分为两部分，1：拦截的路径，2：访问的路径需要的权限
         * authorizeRequests()
         *  表示拦截所有的路径，人喝权限都可以访问
         * .antMatchers("/**").permitAll()
         *  任何请求，authenticated 认证后才能访问
         * .anyRequest().authenticated()
         *  表示让 csrf 拦截失效
         * .and().csrf().disable();
         */

        http.csrf().disable()
                .authorizeRequests()
//                .antMatchers("/r/menu10").hasAnyAuthority("menu10")
                .antMatchers("/r/**").authenticated() // /r/** 请求必须要经过认证
                .anyRequest().permitAll()  // 除了 /r/** 这种请求，其他请求可以访问  不需要认证
                .and().formLogin()
//                .loginPage("/logView")
                .loginProcessingUrl("/login")
                .loginProcessingUrl("/")
                .successForwardUrl("/loginSuccess");
//                .and().logout().logoutUrl("/logout");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
